package com.suixun.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suixun.dao.DevicepurchaseMapper;
import com.suixun.dao.StdIotSimMapper;
import com.suixun.dao.devicemanage.DeviceServiceDAO;
import com.suixun.dao.devicemanage.SimInfoServiceDAO;
import com.suixun.dao.studentmanage.StudentManageDAO;
import com.suixun.entity.Devicepurchase;
import com.suixun.entity.DevicepurchaseExample;
import com.suixun.entity.SimInfo;
import com.suixun.entity.StdIotSim;
import com.suixun.entity.form.SimInfoForm;
import com.suixun.entity.page.PageModel;
import com.suixun.queue.SMSDeal;
import com.suixun.service.SimInfoService;
import com.suixun.util.Constant;
import com.suixun.util.DateUtil;
import com.suixun.util.ExcelUtil;
import com.suixun.util.StringUtil;

@Service
public class SimInfoServiceImpl implements SimInfoService {
	protected final static Logger logger = LoggerFactory.getLogger(SimInfoServiceImpl.class); 
	@Resource
	private SimInfoServiceDAO simfodao;
	@Resource
	private DeviceServiceDAO deviceServiceDao;
	@Resource
	private StudentManageDAO studentManageDAO;
	@Resource
	private DevicepurchaseMapper devicepurchaseMapper;
	@Resource
    private SMSDeal sMSDeal;
	@Resource
	private StdIotSimMapper stdIotSimMapper;

	// 查询某个Sim卡明细
	@Override
	public SimInfo querySimInfoByIccid(SimInfoForm simInfoForm) {
		if (StringUtil.isBlank(simInfoForm.getIccid()))
			return null;
		SimInfo simInfo = simfodao.querySimInfoByIccid(simInfoForm);
		return simInfo;
	}

	// 查询某个Sim卡明细
	@Override
	public SimInfo querySimInfoByID(SimInfoForm simInfoForm) {
		if (StringUtil.isBlank(simInfoForm.getId()))
			return null;
		SimInfo simInfo = simfodao.querySimInfoByID(simInfoForm);
		return simInfo;
	}

	// 查询Sim卡已被使用的次数
	@Override
	public int queryUsedCounts(SimInfoForm simInfoForm) {
		if (StringUtil.isBlank(simInfoForm.getPhone()))
			return -1;
		return simfodao.queryUsedCounts(simInfoForm);
	}

	// 查询Sim卡列表
	@Override
	public List<SimInfo> querySimInfolist(SimInfoForm simInfoForm) {
		if (!StringUtil.isBlank(simInfoForm.getIccid()))
			simInfoForm.setIccid(StringUtil.append(simInfoForm.getIccid()));
		List<SimInfo> devicelist = simfodao.querySimInfolist(simInfoForm);
		return devicelist;
	}

	// 分页查询Sim卡列表
	@Override
	public PageModel<SimInfo> querySimInfolistPage(SimInfoForm simInfoForm) {

		PageModel<SimInfo> pageModel = new PageModel<SimInfo>();
		if (StringUtil.isNotEmpty(simInfoForm.getIccid())) {
			pageModel.getQueryparam().put("iccid", simInfoForm.getIccid());
		}
		if (StringUtil.isNotEmpty(simInfoForm.getPhone())) {
			pageModel.getQueryparam().put("phone", simInfoForm.getPhone());
		}
		if (StringUtil.isNotEmpty(simInfoForm.getStatus())) {
			pageModel.getQueryparam().put("status", simInfoForm.getStatus());
		}

		if (StringUtil.isNotEmpty(simInfoForm.getPagecount())) {
			pageModel.setPagesize(Integer.parseInt(simInfoForm.getPagecount()));
		}
		Integer totleRows = simfodao.countRows(pageModel);
		pageModel.setTotlepage(totleRows);
		if (StringUtil.isNotEmpty(simInfoForm.getPagenumber())) {
			pageModel.setCurrentpage(Integer.parseInt(simInfoForm.getPagenumber()));
		}
		
		List<SimInfo> simInfoList = simfodao.querySimInfolistPage(pageModel);
		if (simInfoList.size() > 0) {
			for (SimInfo siminfo : simInfoList) {
				List<SimInfo> simTempList = simfodao.queryPeopleinfo(siminfo.getId());
				if (simTempList.size() > 0) {
					siminfo.setPeopleidcard(simTempList.get(0).getPeopleidcard());
					siminfo.setPeoplename(simTempList.get(0).getPeoplename());
					siminfo.setMdtid(simTempList.get(0).getMdtid());
				}
			}
		}
		pageModel.setQueryresult(simInfoList);

		return pageModel;
	}

	// 新增Sim卡
	@Override
	@Transactional
	public int addSimInfo(SimInfo simInfo, long operatorid) {
		//查看手机号是否已存在
		Map<String,Object> map = new HashMap<>();
		createTempTable();
		List<SimInfo> tempList = new ArrayList<>();
		tempList.add(simInfo);
		map.put("simTmpList", tempList);
		List<SimInfo> simList = simfodao.queryByParam(map);
		if (simList.size() > 0) {
			return -1;
		}
		simfodao.addSimTmp(map);
		int result = simfodao.addSimInfo(simInfo);
		return result;
	}

	// 修改Sim卡
	@Override
	@Transactional
	public int modifySimInfo(SimInfo simInfo, long operatorid) {
		if (simInfo == null || simInfo.getId() == null)
			return 0;
		int result = simfodao.updateSimInfo(simInfo);
		return result;
	}

	/**
	 * <p>Title: delSimInfo</p>
	 * <p> 功能描述: 注销sim卡</p>
	 * @param ids
	 * @return
	 */
	@Override
	@Transactional
	public int delSimInfo(String ids) {
		if(ids==null || ids.trim().equals(""))
			return 0;
		String[] idArray=ids.split("[|]");
		StdIotSim stdIotSim = null;
		for(String id : idArray) {
			stdIotSim = new StdIotSim();
			stdIotSim.setId(Integer.parseInt(id));
			stdIotSim.setStatus((byte)-1);
			stdIotSimMapper.updateByPrimaryKeySelective(stdIotSim);
		}
		return 1;
	}

	
	
	/**
	 * <p>Title: importSim</p>
	 * <p> 功能描述:导入excel </p>
	 * @param paramForm
	 * @return
	 */
	@Override
	@Transactional
	public String importSim(HSSFWorkbook wb) {
		//long start = System.currentTimeMillis();
		//检验合法性
		String[] title={Constant.Excel.OPERATIONS,Constant.Excel.SIM,Constant.Excel.ICCID};
		String check=ExcelUtil.checkExcel(wb,title,false);
		if(!check.equals(Constant.TRUE)){
			return check;
		}
		//logger.debug("校验合法性耗时---"+(System.currentTimeMillis()-start)+"ms");
		//检验excel表内是否有重复数据
		String[] excelTemplate={Constant.Excel.SIM,Constant.Excel.ICCID};
		String isRepeat=ExcelUtil.checkRepeat(wb,excelTemplate);
		if(!isRepeat.equals(Constant.TRUE)){
			return isRepeat;
		}
		//logger.debug("校验重复数据耗时---"+(System.currentTimeMillis()-start)+"ms");
		//将数据添加到simList集合中
		List<SimInfo> simList=new LinkedList<>();
		HSSFSheet sheet = wb.getSheetAt(0);
		int rowSize = sheet.getLastRowNum()+1;
		int colSize = sheet.getRow(0).getLastCellNum();
		for(int j=1;j<rowSize;j++){
			int count=0;
			SimInfo sim=new SimInfo();
			//创建一个行对象
			HSSFRow row = sheet.getRow(j);
			for(int i=0;i<colSize;i++){
				if (row.getCell(i) == null) {
					count++;
					continue;
				}
				row.getCell(i).setCellType(CellType.STRING);
				if(i<=2){
					if(row.getCell(i).getRichStringCellValue()==null||!StringUtil.isNotEmpty(row.getCell(i).getRichStringCellValue().toString())){
						count++;
					}
				}
			}
			if(count>=3){
				continue;
			}
			sim.setOperations(row.getCell(0).getRichStringCellValue().toString());
			sim.setPhone(row.getCell(1).getRichStringCellValue().toString());
			//检查std_iot_sim表中是否存在当前手机号和iccid
			sim.setIccid(row.getCell(2).getRichStringCellValue().toString());
			simList.add(sim);
		}
		//logger.debug("组装数据耗时---"+(System.currentTimeMillis()-start)+"ms");
		//创建临时表
		createTempTable();
		//创建临时重复表
		createRepeatTable();
		//logger.debug("创建临时表耗时---"+(System.currentTimeMillis()-start)+"ms");
		int count = simList.size() % Constant.Excel.NUM == 0 ? simList.size()/Constant.Excel.NUM : simList.size()/Constant.Excel.NUM+1;
		Map<String,Object> map=new HashMap<>();
		for (int i = 0 ; i < count ; i ++) {
			List<SimInfo> tempList =  new LinkedList<>();
			for (int j = i * Constant.Excel.NUM ; j < (i+1) * Constant.Excel.NUM ; j ++ ) {
				if (j < simList.size()) {
					tempList.add(simList.get(j));
				}
			}
			map.put("simTmpList", tempList);
			simfodao.addSimTmp(map);
		}
		//logger.debug("添加数据到临时表耗时---"+(System.currentTimeMillis()-start)+"ms");
		//添加数据到std_iot_sim表
		Integer isAdd=simfodao.importSim();
		//logger.debug("存储过程耗时---"+(System.currentTimeMillis()-start)+"ms");
		String result=null;
		if(isAdd==1){
			result=Constant.Excel.EXCEL_IS_EXIST;
		}else{
			result=Constant.Excel.IMPORT_TRUE;
		}
		return result;
	}
	
	/**
	 * <p>Title: createTable</p>
	 * <p> 功能描述:创建临时表 </p>
	 */
	@Transactional
	public void createTempTable() {
		simfodao.createTmpTable();
		Integer isExist = simfodao.queryTempIndex();
		if (isExist == 0) {
			simfodao.addTempIndex();
		}
		simfodao.deleteTmpTable();
	}
	/**
	 * <p>Title: createRepeatTable</p>
	 * <p> 功能描述:创建临时重复表，若数据库里有重复数据，则将重复数据添加到重复表中 </p>
	 */
	public void createRepeatTable() {
		simfodao.createRepeatTable();
		simfodao.deleteRepeatTable();
	}

	/**
	 * <p>Title: querySimTmp</p>
	 * <p> 功能描述:查看最近一次导入数据 </p>
	 * @param simInfoForm
	 */
	@Override
	public PageModel<SimInfo> querySimTmp(SimInfoForm simInfoForm) {
		PageModel<SimInfo> pageModel = new PageModel<SimInfo>();
		if (StringUtil.isNotEmpty(simInfoForm.getPagecount())) {
			pageModel.setPagesize(Integer.parseInt(simInfoForm.getPagecount()));
		}
		try{
			Integer totleRows = simfodao.querySimTmpRows();
			pageModel.setTotlepage(totleRows);
			if (StringUtil.isNotEmpty(simInfoForm.getPagenumber())) {
				pageModel.setCurrentpage(Integer.parseInt(simInfoForm.getPagenumber()));
			}
			List<SimInfo> simInfoList = simfodao.querySimTmp(pageModel);
			for(SimInfo sim:simInfoList){
				sim.setCreatetimestr(DateUtil.formatDateToString(sim.getCreatetime(), null));
			}
			pageModel.setQueryresult(simInfoList);
		}catch(Exception e){
			
		}
		return pageModel;
	}

	/**
	 * <p>Title: cancelSimImport</p>
	 * <p> 功能描述:撤销最近一次入库 </p>
	 * @return
	 */
	@Override
	@Transactional
	public int cancelSimImport() {
		//查询最近一次入库的数据是否已被使用
		try{
			List<SimInfo> list=simfodao.querySimTmpInSim();
			if(list.size()!=0){
				return -1;
			}
		}catch(Exception e){
			return -2;
		}
		int isdelete=simfodao.deleteSimTmpInSim();
		simfodao.deleteTmpTable();
		simfodao.deleteRepeatTable();
		return isdelete;
	}
	/**
	 * 
	 * <p>Title: queryIsBind</p>
	 * <p> 功能描述:查看临时表数据是否已被绑定 </p>
	 * @return
	 */
	public List<SimInfo> queryIsBind(){
		return simfodao.querySimTmpInSim();
	}

	@Override
	public List<SimInfo> querySimRepeat() {
		return simfodao.queryRepeatTable();
	}

	@Override
	public void notPass(String orderno) {
		
		DevicepurchaseExample example = new DevicepurchaseExample();
		example.createCriteria().andOrdernoEqualTo(orderno).andStatusEqualTo(1);
		example.or(example.createCriteria().andOrdernoEqualTo(orderno).andStatusIsNull());
		
		List<Devicepurchase> list = devicepurchaseMapper.selectByExample(example);
		if(list == null || list.isEmpty()){
			throw new RuntimeException("订单已取消或不存在");
		}
		Devicepurchase devicepurchase = list.get(0);
		
		Map<String, String> smsMap = new HashMap<String, String>();
		smsMap.put("module", "auth");
		smsMap.put("telephone", devicepurchase.getTelephone());
		//smsMap.put("url", "www.17find.com/buy/#buy/"+devicepurchase.getId());
		smsMap.put("url", "http://wx.17find.com/buycq/#/buy/ss"+devicepurchase.getId());
		sMSDeal.send(smsMap);
		
		devicepurchase.setSmspush((short)1);
		devicepurchaseMapper.updateByPrimaryKey(devicepurchase);
		
	}
}
